<template>
  <div class="product-detail">
    <!-- 头部区域 -->
    <header class="detail-nav" >
      <i class="iconfont icon-left" @click="goBack"></i>
      <div class="nav-list">
        <span
          :class="{ active: navIndex === 0 }"
          data-type="product"
          @click="scrollToView($event);goTop()"
        >
          <i class="iconfont icon-location" v-show="navIndex === 0"></i>商品
        </span>
        <span
          :class="{ active: navIndex === 1 }"
          data-type="detail"
          @click="scrollToView($event);goDetail()"
        >
          <i class="iconfont icon-location" v-show="navIndex === 1"></i>商品详情
        </span>
        <span
          :class="{ active: navIndex === 2 }"
          data-type="recommend"
          @click="scrollToView($event);goTop()"
           href="#detail-nav"
        >
          <i class="iconfont icon-location" v-show="navIndex === 2" ></i>商品推荐
        </span>
      </div>
      <i class="iconfont icon-More"></i>
    </header>
    <!-- 轮播图 -->
    <section class="product-focus">
      <van-swipe
        :autoplay="3000"
        indicator-color="white"
        class="swiper-container"
      >
        <van-swipe-item v-for="(item, index) in sliderImageList" :key="index">
          <img :src="item.imgUrl" class="swiper_img" alt="" />
        </van-swipe-item>
      </van-swipe>
    </section>
    <!-- 详情信息 -->
    <section class="detail-info" >
      <p class="detail-info-name">{{ productDetail.name }}</p>
      <p class="detail-info-subtitle">{{ productDetail.subtitle }}</p>
      <div id="content">
        <span class="detail-info-price">￥{{ productDetail.price }}</span>
        <span class="detail-info-stock">库存{{ productDetail.stock }}件</span>
      </div>
    </section>
    <!-- 商品详情 -->
    <section class="detail-content" ref="detailContent"  name="content">
      <p class="detail-gap"></p>
      <ul>
        <li>概述</li>
        <li>参数</li>
        <li>安装服务</li>
        <li>常见问题</li>
      </ul>
      <div v-html="productDetail.detail"></div>
    </section>
    <!-- 底部商品 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="cart-o" text="购物车" :info="this.$store.getters.getBadgeCount.allCount" @click="goShopcart"/>
      <van-goods-action-button type="warning" text="加入购物车" @click="show=true" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
      @stepper-change = "onStepperChange"
    />
  </div>
</template>
<script>
import { getProcuctDetail,submitToCar } from "@/http/index";
export default {
  data() {
    return {
      // 接收传递的参数
      id: this.$route.params.id,
      //导航栏高亮属性
      navIndex: 0,
      // 数据列表
      productDetail: {},
      // 保存轮播图数据
      sliderImageList: [],
      //选择的数量
      count:1,
      show: false,
      sku: {
      },
      goodsId:this.$route.params.id,
      goods: {
        // 商品标题
        title: "测试商品",
        // 默认商品 sku 缩略图
        picture:
          "http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg",
      },
    };
  },
  methods: {
    // 返回
    goBack() {
      this.$router.go(-1);
    },
    //导航栏高亮选择
    scrollToView(e) {
      let dataType = e.target.getAttribute("data-type");
      switch (dataType) {
        case "product":
          this.navIndex = 0;
          break;
        case "detail":
          this.navIndex = 1;
          break;
        case "recommend":
          this.navIndex = 2;
          break;
      }
    },
    // 商品数据
    fetchProductDetail() {
      const params = {
        id: this.id,
      };
      getProcuctDetail(params).then((res) => {
        this.productDetail = res;
        // 图片地址列表
        let subImages = res.subImages.split(",");
        //图片地址头
        let imageHost = res.imageHost;
        subImages.forEach((item) => {
        // 将图片地址拼接装入数组
        this.sliderImageList.push({ imgUrl: imageHost + item });
        
        });
        //设置卡片信息
        this.setSku()
      });
    },
    //点击购买回调
    onBuyClicked() {
      console.log("点击了购买");
    },
    //点击添加购物车回调
    onAddCartClicked() {
        const params = {
            productId:this.id,
            count:this.count
        }
        //组装商品id和商品数量作为参数发送请求
        submitToCar(params).then(res=>{
            if(res.status == 0){
                this.$router.push('/shopcart')
            }else{
                this.$toast(res.msg)
            }
        })
    },
    // 购买数量变化时触发
    onStepperChange(value){
      console.log(value);
      this.count=value;
    },
    //点击商品详情
    goDetail(){
      document.querySelector("#content").scrollIntoView(true);
    },
    //点击商品推荐
    goTop(){
       document.documentElement.scrollTop=0
    },
    //购物车卡片的数据设置
    setSku(){
      this.sku={
          tree: [
              {
                k: "颜色", // skuKeyName：规格类目名称
                k_s: "s1", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                v: [
                  {
                    id: "001", // skuValueId：规格值 id
                    name: "红色", // skuValueName：规格值名称
                    imgUrl:
                      this.sliderImageList[0].imgUrl, // 规格类目图片，只有第一个规格类目可以定义图片
                    previewImgUrl:
                      this.sliderImageList[0].imgUrl, // 用于预览显示的规格类目图片
                  },
                  {
                    id: "002",
                    name: "蓝色",
                    imgUrl:
                      this.sliderImageList[1].imgUrl,
                    previewImgUrl:
                      this.sliderImageList[1].imgUrl,
                  },
                ],
             
              },
            ],
            list: [
              {
                id: 2259, // skuId，下单时后端需要
                price: this.productDetail.price*100, // 价格（单位分）
                s1: "001", // 规格类目 k_s 为 s1 的对应规格值 id
                stock_num:this.productDetail.stock-0, // 当前 sku 组合对应的库存
              },
              {
                id: 2259, // skuId，下单时后端需要
                price: 100, // 价格（单位分）
                s1: "002", // 规格类目 k_s 为 s1 的对应规格值 id
                stock_num: 50, // 当前 sku 组合对应的库存
              },
            ],
            price: this.productDetail.price+'.00', // 默认价格（单位元）
            stock_num: this.productDetail.stock-0, // 商品总库存
            collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
            none_sku: false, // 是否无规格商品
      }
    },
    //去购物车页面
    goShopcart(){
       this.$router.push('/shopcart')
    }

  },
  created() {
    this.fetchProductDetail();
 
  },
};
</script>
<style lang="scss" >
// 公共样式
@import "../../common/style/mixin";
// 单独样式
@import "../../css/product-detail";
</style>